/*****************************************
  NAME: Adcts.c
  DESC: ADC & Touch screen test
  WWW.YCTREK.COM
 *****************************************/
#include <string.h>
#include "def.h"
#include "2410addr.h"
#include "2410lib.h"


#define REQCNT 30
#define ADCPRS 9
#define LOOP 1

int ReadAdc(int ch);
void __irq AdcTsAuto(void);

int count=0;
volatile int xdata, ydata;

void Test_Adc(void)
{
    int a0=0,a1=0;
    int i,j;

    Uart_Printf("The ADC_IN are adjusted to the following values.\n");        
    Uart_Printf("Push any key to exit!\n");    
    Uart_Printf("ADC conv. freq.=%d(Hz)\n",(int)(PCLK/(ADCPRS+1.)));
    
    while(Uart_GetKey()==0)
    {

    a0=ReadAdc(0);
    a1=ReadAdc(1);
    Uart_Printf("AIN0: %04d,   AIN1: %04d\n", a0 ,a1);
   
    for (i=0;i<3000;i++)
    {
    	for (j=0;j<10000;j++) ;
    }
    }
    
    rADCCON=(0<<14)+(19<<6)+(7<<3)+(1<<2); 
    Uart_Printf("rADCCON = 0x%x\n", rADCCON);
}

        
int ReadAdc(int ch)
{
    int i;
    static int prevCh=-1;

    if(prevCh!=ch)
        {
        rADCCON=(1<<14)+(ADCPRS<<6)+(ch<<3);
        for(i=0;i<LOOP;i++);
        prevCh=ch;
        }
    rADCCON=(1<<14)+(ADCPRS<<6)+(ch<<3);
    rADCTSC = rADCTSC & 0xfb;
    rADCCON|=0x1;

    while(rADCCON & 0x1);
    while(!(rADCCON & 0x8000));
    return (rADCDAT0&0x3ff);
}

    
void Test_AdcTs(void)
{
   
    rADCDLY=50000;
    rADCCON=(1<<14)+(ADCPRS<<6);

    Uart_Printf("[ADC touch screen test.]\n");

    rADCTSC=0xd3;

    pISR_ADC = (int)AdcTsAuto;
	rINTMSK=~BIT_ADC;
	rINTSUBMSK=~(BIT_SUB_TC);

	Uart_Printf("\nType any key to exit!\n");
	Uart_Printf("\nStylus Down, please...... \n");
	Uart_Getch();

	rINTSUBMSK|=BIT_SUB_TC;
	rINTMSK|=BIT_ADC;
	Uart_Printf("[Touch Screen Test.]\n");

}


void __irq AdcTsAuto(void)
{
	int i;
	U32 saveAdcdly;

    if(rADCDAT0&0x8000)
    {
	Uart_Printf("\nStylus Up!\n");
	rADCTSC&=0xff;
    }
    else 
	Uart_Printf("\nStylus Down!\n");

	rADCTSC=(1<<3)|(1<<2);
	saveAdcdly=rADCDLY;
	rADCDLY=40000;

	rADCCON|=0x1;

		while(rADCCON & 0x1);
		while(!(rADCCON & 0x8000));
		
            while(!(rSRCPND & (BIT_ADC)));

            xdata=(rADCDAT0&0x3ff);
            ydata=(rADCDAT1&0x3ff);

	 rSUBSRCPND|=BIT_SUB_TC;
	 ClearPending(BIT_ADC);
	 rINTSUBMSK=~(BIT_SUB_TC);
	 rINTMSK=~(BIT_ADC);
			 
	 rADCTSC =0xd3;
	 rADCTSC=rADCTSC|(1<<8);

			while(1)
			{
			 if(rSUBSRCPND & (BIT_SUB_TC))
				 {
					Uart_Printf("Stylus Up Interrupt!\n");
					break;
				}
			}	

    Uart_Printf("count=%d XP=%04d, YP=%04d\n", count++, xdata, ydata);     

	rADCDLY=saveAdcdly; 
	rADCTSC=rADCTSC&~(1<<8);
    rSUBSRCPND|=BIT_SUB_TC;
    rINTSUBMSK=~(BIT_SUB_TC); 
    ClearPending(BIT_ADC);
}
